package com.base.dp;

public class LongestCommonSubsequence {
    public static void main(String[] args) {
        LongestCommonSubsequence longestCommonSubsequence = new LongestCommonSubsequence();
        System.out.println(longestCommonSubsequence.longestCommonSubsequence("abc", "def"));
    }

    public int longestCommonSubsequence(String text1, String text2) {
        // 定义dp[i][j]表示字符串text1下标i，text2下标j，最长公共子序列
        int m = text1.length();
        int n = text2.length();
        int[][] dp = new int[m][n];
        //初始化
        dp[0][0] = text1.charAt(0) == text2.charAt(0) ? 1 : 0;
        for (int i = 1; i < m; i++) {
            if (text1.charAt(i) == text2.charAt(0)) {
                dp[i][0] = 1;
            } else {
                dp[i][0] = dp[i - 1][0];
            }
        }
        for (int j = 1; j < n; j++) {
            if (text1.charAt(0) == text2.charAt(j)) {
                dp[0][j] = 1;
            } else {
                dp[0][j] = dp[0][j - 1];
            }
        }
        /**
         *   1 1 1 1
         *   1
         *   1
         *   1
         *   1
         *
         *
         */
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                //当前i行i列   比如 i =1  j=1;
                if (text1.charAt(i) == text2.charAt(j)) {
                    //第二个字符和第二个字符相等
                    // 是不是可以加入到前面的公共子序列呢？
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[m - 1][n - 1];
    }
}
